{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "da1df782-bdb2-415c-b80a-045aacba0c63",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User-CF和余弦相似度的推荐结果:\n",
      "为用户 A 推荐的物品: ['a', 'c']\n",
      "为用户 B 推荐的物品: ['d', 'e']\n"
     ]
    }
   ],
   "source": [
    "#User-CF和余弦相似度的推荐结果:\n",
    "import numpy as np  \n",
    "  \n",
    "data =[ ['A','b'],['A','d'],['B','a'],['B','b'],['B','c'],['C','a'],['C','b'],['C','d'],['D','a'],['D','e']]\n",
    "\n",
    "# 创建用户和物品的映射  \n",
    "users = {}    \n",
    "items = {}    \n",
    "for user, item in data:  \n",
    "    if user not in users:  \n",
    "        users[user] = len(users)  # 修正为 users[user]  \n",
    "    if item not in items:  \n",
    "        items[item] = len(items)  \n",
    "  \n",
    "# 构建用户-物品交互矩阵  \n",
    "num_users = len(users)    \n",
    "num_items = len(items)    \n",
    "interaction_matrix = np.zeros((num_users, num_items))    \n",
    "  \n",
    "for user, item in data:    \n",
    "    interaction_matrix[users[user], items[item]] = 1  \n",
    "  \n",
    "# 计算余弦相似度  \n",
    "def cosine_similarity(matrix):    \n",
    "    sim = np.dot(matrix, matrix.T)    \n",
    "    norms = np.sqrt(np.diag(sim))  # 修正为 np.sqrt(np.diag(sim))  \n",
    "    return sim / norms / norms[:, np.newaxis]  # 修正为 norms[:, np.newaxis] 以进行广播  \n",
    "  \n",
    "similarity = cosine_similarity(interaction_matrix)    \n",
    "  \n",
    "# 为用户生成推荐  \n",
    "def recommend(user_index, interaction_matrix, similarity, k=1):    \n",
    "    user_similarities = similarity[user_index]    \n",
    "      \n",
    "    # 计算用户未评分物品的预测评分  \n",
    "    scores = interaction_matrix.T.dot(user_similarities)    \n",
    "      \n",
    "    # 排除已评分的物品  \n",
    "    user_interactions = interaction_matrix[user_index]  \n",
    "    scores[user_interactions > 0] = 0    \n",
    "      \n",
    "    # 获取Top K推荐的物品  \n",
    "    recommended_indices = np.argsort(scores)[::-1][:k]    \n",
    "    return [list(items.keys())[i] for i in recommended_indices]    \n",
    "\n",
    "print(\"User-CF和余弦相似度的推荐结果:\")  \n",
    "# 示例：为用户 A (index 0) 生成推荐  \n",
    "user_index = users['A']    \n",
    "recommended_items = recommend(user_index, interaction_matrix, similarity, k=2)    \n",
    "print(\"为用户 A 推荐的物品:\", recommended_items)    \n",
    "  \n",
    "# 示例：为用户 B (index 1) 生成推荐  \n",
    "user_index = users['B']    \n",
    "recommended_items = recommend(user_index, interaction_matrix, similarity, k=2)\n",
    "print(\"为用户 B 推荐的物品:\", recommended_items)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0ae67eba-4555-489c-866c-bc50a8206341",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Item-CF和杰卡德相似度的推荐结果\n",
      "为用户 A 推荐的物品: ['a', 'c']\n",
      "为用户 B 推荐的物品: ['e', 'd']\n"
     ]
    }
   ],
   "source": [
    "#Item-CF和杰卡德相似度的推荐结果:\n",
    "import numpy as np  \n",
    "  \n",
    "data =[ ['A','b'],['A','d'],['B','a'],['B','b'],['B','c'],['C','a'],['C','b'],['C','d'],['D','a'],['D','e']]\n",
    "\n",
    "  \n",
    "# 创建用户和物品的映射  \n",
    "users = {}  \n",
    "items = {}  \n",
    "for user, item in data:  \n",
    "    if user not in users:  \n",
    "        users[user] = len(users)  \n",
    "    if item not in items:  \n",
    "        items[item] = len(items)  \n",
    "  \n",
    "# 构建用户-物品交互矩阵  \n",
    "num_users = len(users)  \n",
    "num_items = len(items)  \n",
    "interaction_matrix = np.zeros((num_users, num_items))  \n",
    "  \n",
    "for user, item in data:  \n",
    "    interaction_matrix[users[user], items[item]] = 1  \n",
    "  \n",
    "# 计算杰卡德相似度  \n",
    "def jaccard_similarity(interaction_matrix):  \n",
    "    item_count = interaction_matrix.shape[1]  \n",
    "    similarity = np.zeros((item_count, item_count))  \n",
    "  \n",
    "    for i in range(item_count):  \n",
    "        for j in range(i + 1, item_count):  # 只需要计算上三角矩阵  \n",
    "            users_i = np.where(interaction_matrix[:, i] == 1)[0]  \n",
    "            users_j = np.where(interaction_matrix[:, j] == 1)[0]  \n",
    "            intersection = len(np.intersect1d(users_i, users_j))  \n",
    "            union = len(np.union1d(users_i, users_j))  \n",
    "            if union != 0:  \n",
    "                similarity[i, j] = intersection / union  \n",
    "                similarity[j, i] = similarity[i, j]  # 确保对称性  \n",
    "    return similarity  \n",
    "  \n",
    "# 为用户生成推荐（基于杰卡德相似度）  \n",
    "def recommend_items(user_index, interaction_matrix, item_similarity, k=1):  \n",
    "    user_items = np.where(interaction_matrix[user_index] == 1)[0]  # 用户已交互的物品索引  \n",
    "    scores = np.zeros(interaction_matrix.shape[1])  \n",
    "  \n",
    "    # 根据用户已交互的物品和物品相似度计算推荐分数  \n",
    "    for item in user_items:  \n",
    "        scores += item_similarity[item]  \n",
    "  \n",
    "    # 归一化分数（可选，但在这里有助于解释结果）  \n",
    "    scores /= np.sum(item_similarity, axis=0)  \n",
    "  \n",
    "    # 排除已交互的物品（将它们的分数设为负无穷大或一个非常小的数，然后排序时忽略）  \n",
    "    scores[user_items] = -np.inf  # 或者使用 scores[user_items] = 0 并在后续处理中忽略最高分（如果是0）的项  \n",
    "  \n",
    "    # 获取Top K推荐的物品索引  \n",
    "    recommended_indices = np.argsort(scores)[::-1][:k]  \n",
    "    # 注意：如果使用了-np.inf，这里需要过滤掉-np.inf的索引  \n",
    "    recommended_indices = [idx for idx in recommended_indices if scores[idx] != -np.inf]  \n",
    "  \n",
    "    return [list(items.keys())[i] for i in recommended_indices]  \n",
    "  \n",
    "# 计算杰卡德相似度  \n",
    "item_similarity = jaccard_similarity(interaction_matrix)  \n",
    "\n",
    "print(\"Item-CF和杰卡德相似度的推荐结果\")    \n",
    "# 示例：为用户 A (index 0) 生成推荐  \n",
    "user_index = users['A']  \n",
    "recommended_items_A = recommend_items(user_index, interaction_matrix, item_similarity, k=2)  \n",
    "print(\"为用户 A 推荐的物品:\", recommended_items_A)  \n",
    "  \n",
    "# 示例：为用户 B (index 1) 生成推荐  \n",
    "user_index = users['B']  \n",
    "recommended_items_B = recommend_items(user_index, interaction_matrix, item_similarity, k=2)  \n",
    "print(\"为用户 B 推荐的物品:\", recommended_items_B)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab1cf6ea-a11b-4ae7-abc9-9bf15702fe6e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
